<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button
      v-if="draggable == true"
      type="success"
      round
      @click="() => updateSort(data)"
      >批量更新</el-button
    >
    <el-button type="danger" round @click="() => batchDelete(data)"
      >批量删除</el-button
    >

    <el-tree
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      ref="tree"
      show-checkbox
      node-key="catId"
      @node-drop="handleDrop"
      :default-expanded-keys="expandKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>

          <el-button
            type="text"
            size="mini"
            @click="() => queryInfo(data)"
          >
            更新
          </el-button>

          <el-button
            v-if="data.childrens && data.childrens.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
          
        </span>
      </span>
    </el-tree>

    <!-- 弹出框 -->
    <el-dialog
      :title="dialogUpdate ? `更新` : `添加`"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="categoryForm">
        <el-form-item label="类别名称">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="categoryForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="categoryForm.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  data() {
    return {
      parentIds: [], //拖拽后的父节点数组
      draggable: false, //默认拖拽功能关闭
      updateNodes: [], //拖拽节点后,需要更新的节点信息
      maxLevel: 0,
      dialogUpdate: false,
      dialogVisible: false,
      categoryForm: {
        name: null,
        icon: null,
        productUnit: null,
        showStatus: 1,
        catId: null,
        sor: 0,
        catLevel: null,
      },
      data: [],
      expandKeys: [],
      defaultProps: {
        children: "childrens",
        label: "name",
      },
    };
  },
  created() {
    this.getMenuDataList();
  },
  methods: {
    // 获取数据列表
    getMenuDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/treeList"),
        method: "get",
      }).then(({ data }) => {
        // console.log(data);
        this.data = data.list;
        this.dataListLoading = false;
      });
    },
    append(data) {
      //打开窗口
      this.dialogVisible = true;
      this.categoryForm.parentCid = data.catId;
      this.categoryForm.catLevel = data.catLevel + 1;
      this.categoryForm.showStatus = 1;
      this.categoryForm.sort = 0;
      this.dialogUpdate = false;
    },
    submitForm(data) {
      if (this.dialogUpdate == true) {
        this.editDialog(data);
      } else {
        this.addDialog(data);
      }
    },
    cancelForm(data) {
      this.dialogVisible = false;
      this.resetCategoryForm();
    },
    resetCategoryForm() {
      this.categoryForm = {
        name: null,
        icon: null,
        productUnit: null,
        showStatus: 1,
        catId: null,
        sor: 0,
        catLevel: null,
      };
    },
    editDialog(data) {
      //修改类别信息
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "数据更新成功",
              type: "success",
              duration: 1500,
            });
            //关闭窗口
            this.dialogVisible = false;
            //重新加载所有数据
            this.getMenuDataList();
            //默认展开位置
            this.expandKeys = [this.categoryForm.catId];
            //重置更新数据
            this.resetCategoryForm();
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch((err) => {
          this.$message("操作失败");
        });
    },
    addDialog(data) {
      //添加类别信息
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "数据添加成功",
              type: "success",
              duration: 1500,
            });
            //关闭窗口
            this.dialogVisible = false;
            //重新加载所有数据
            this.getMenuDataList();
            //默认展开位置
            this.expandKeys = [this.categoryForm.parentCid];
            //重置更新数据
            this.resetCategoryForm();
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch((err) => {
          this.$message("操作失败");
        });
    },
    remove(node, data) {
      this.$confirm(`是否删除${data.name}菜单`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        //传递的数据
        let ids = [data.catId];

        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        })
          .then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
              });
              //重新加载所有数据
              this.getMenuDataList();
              //默认展开位置
              this.expandKeys = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          })
          .catch((err) => {
            this.$message("操作失败");
          });
      });
    },
    batchDelete(data) {
      //批量删除方法
      let catIds = [];
      let checkedNodes = this.$refs.tree.getCheckedNodes(false, false);
      console.log(checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
      }
      this.$confirm(`是否删除多个菜单`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        //传递的数据
        let ids = catIds;

        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        })
          .then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
              });
              //重新加载所有数据
              this.getMenuDataList();
            } else {
              this.$message.error(data.msg);
            }
          })
          .catch((err) => {
            this.$message("操作失败");
          });
      });
    },
    queryInfo(data) {
      this.dialogUpdate = true;
      //获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        //表单数据回写
        this.categoryForm.name = data.category.name;
        this.categoryForm.icon = data.category.icon;
        this.categoryForm.productUnit = data.category.productUnit;
        this.categoryForm.catLevel = data.category.catLevel;

        //补充完善信息
        this.categoryForm.catId = data.category.catId;
        this.categoryForm.showStatus = 1;
        this.categoryForm.sort = 0;

        //打开窗口
        this.dialogVisible = true;
      });
    },
    handleDrop(draggingNode, dropNode, type, event) {
      //1.拖拽节点的父节点需要修改
      let parentId = 0;
      // 找到拖拽节点对应的所有的兄弟节点
      let siblings = null;
      if (type == "inner") {
        parentId = dropNode.data.catId;
        //找到拖拽节点对应的所有兄弟节点
        siblings = dropNode.childNodes;
      } else {
        parentId =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        //找到目标节点的父节点下的所有子节点
        siblings = dropNode.parent.childNodes;
      }

      //2.拖拽后节点所在的新的兄弟节点间的排序问题
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //获取的就是拖拽的那个节点 我们需要更新parent_id
          //3.拖拽后的节点及其节点的catLevel更新问题
          let catLevel = draggingNode.level;
          if (siblings[i].level != catLevel) {
            //拖拽后节点层级发生变化
            catLevel = siblings[i].level;
            //递归的方式来更新子节点层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: parentId,
            catLevel: catLevel,
          });
        }
        this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
      }

      //校验拖拽后数据
      // console.log("------>", this.updateNodes);
      // this.updateSort(parentId);
      this.parentIds.push(parentId);
    },
    updateSort() {
      //批量更新拖拽后的数据 层级+排序
      this.$http({
        url: this.$http.adornUrl("/product/category/updateBatch"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "数据拖拽成功",
              type: "success",
            });
            //重新加载所有数据
            this.getMenuDataList();
            //默认展开位置
            this.expandKeys = this.parentIds;
            //重置存储拖拽数据的容器
            this.updateNodes = [];
            this.maxLevel = 0;
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch((err) => {
          this.$message("操作失败");
        });
    },
    updateChildNodeLevel(node) {
      //查找拖拽节点的子节点最大level
      this.maxLevel = node.data.catLevel;

      if (node.childNodes != null && node.childNodes.legth > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var chilNode = node.childNodes[i].data;

          this.updateNodes.push({
            catId: node.childNodes.catId,
            catLevel: node.childNodes[i].level,
          });
          //如果还有子节点,同步更新
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      //type prev inner next 目标节点的前驱  自身 后继
      //draggingNode 要拖拽的节点  dropNode目标节点

      // console.log("--->", draggingNode, dropNode, type);

      //获取当前被拖拽的节点最大level
      this.countNodeLevel(draggingNode);
      //做abs的原因是有可能为负数
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;

      //判断拖拽的节点是否能在该位置放置
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      //找到所有子节点最大的Level
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
  },
};
</script>

<style>
</style>